/*
 商品分类模块
*/
import { topCategory } from '@/api/constants'
import { findAllCategory } from '@/api/category'

export default {
  namespaced: true,
  state () {
    return {
      // 分类信息集合
      list: topCategory.map(item => ({ name: item }))
    }
  },

  mutations: {
    // 修改分类
    setList (state, headCategory) {
      state.list = headCategory
    },
    // 修改当前一级分类下的open数据为true
    show (state, item) {
      const currCategory = state.list.find(category => category.id === item.id)
      currCategory.open = true
    },
    // 修改当前一级分类下的open数据为false
    hide (state, item) {
      const currCategory = state.list.find(category => category.id === item.id)
      currCategory.open = false
    }
  },
  actions: {
    // 从vuex中解构出commit
    async getList ({ commit }) {
      const { result } = await findAllCategory()

      // 设置变量控制二级菜单的显示和以及隐藏
      result.forEach(item => { item.open = false })

      // 获取数据成功，提交mutations进行数据修改
      commit('setList', result)
    }
  }
}
